﻿using NIDViewer.Enums;
using NIDViewer.FlattenImage;
using NIDViewer.Model;
using NumSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NIDViewer
{
    public class DpService
    {
        /// <summary>
        /// 图像拉平功能
        /// </summary>
        public FlattenImageResponse FlattenImage(FlattenImageRequest request)
        {
            var arr = np.array(request.Matrix);
            var line_point_number = request.Points;
            var total_length = arr.size;
            var line_number = total_length / line_point_number;
            var resize_arr = arr.reshape((line_number), (line_point_number));

            NDArray? mask = null;
            if (np.array(request.Mask).size != 0)
            {
                var mask_arr = np.array(request.Mask);
                var mask_length = mask_arr.size;
                if (total_length != mask_length)
                {
                    throw new Exception("DP:The size of the mask does not match the size of the input data.");
                }
                var array_2d = mask_arr.reshape((line_number), (line_point_number));
                mask = array_2d.astype(typeof(bool));
            }

            NDArray imageFlat;
            switch (request.FlattenType)
            {
                case FlattenAlgorithm.PER_LINE_1:
                    var result = ImageProcessor.FlattenPerLine1(resize_arr, mask);
                    imageFlat = result.Item1;
                    break;
                default:
                    throw new ArgumentException("Provided flatten algorithm is of wrong type.");
            }
            return new FlattenImageResponse
            {
                Matrix = imageFlat.ToArray<double>().ToList(),
                IsError = false,
            };
        }
    }
}
